import React, { useEffect } from 'react';

/**
 * 矩形的制作
 */
export default (props) => {
  useEffect(() => {
    init();
  }, []);
  const init = () => {
    let canvas = document.getElementById('rect_id');
    const gl = canvas.getContext('webgl');
    //顶点着色器源码(顶点的渲染位置和渲染的点的像素大小)
    const vertexShaderSource = `
           void main(){
               gl_PointSize=100.0;
               gl_Position =vec4(0.0,0.0,0.0,1.0);
           }
        `;
    //片元着色器源码（渲染的点的颜色--红色rgba）
    const fragShaderSource = `
            void main() {
                gl_FragColor = vec4(1.0,0.0,0.0,1.0);
            }
        `;
    //初始化着色器
    const program = initShader(gl, vertexShaderSource, fragShaderSource);
    //开始绘制，显示器显示结果
    gl.drawArrays(gl.POINTS, 0, 1);
  };
  // 完成着色器代码的编译，然后在CPU上执行
  const initShader = (gl, vertexShaderSource, fragmentShaderSource) => {
    //创建顶点着色器对象
    const vertexShader = gl.createShader(gl.VERTEX_SHADER);
    // 创建片元着色器对象
    const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
    //引入顶点、片元着色器源代码
    gl.shaderSource(vertexShader, vertexShaderSource);
    gl.shaderSource(fragmentShader, fragmentShaderSource);
    //编译顶点、片元着色器
    gl.compileShader(vertexShader);
    gl.compileShader(fragmentShader);
    //创建程序对象program
    const program = gl.createProgram();
    //附着顶点着色器和片元着色器到program
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    //链接program
    gl.linkProgram(program);
    //使用program
    gl.useProgram(program);
    //返回程序program对象
    return program;
  };
  return (
    <>
      <div>
        <canvas id="rect_id"></canvas>
      </div>
    </>
  );
};
